#!/usr/bin/env python3
# Copyright (c) 2019-2020 Windy Albert

import hashlib
from ecdsa import SECP256k1
import ecdsa
import os
import base58check
import pyqrcode
import sha3

import pyqrcode

import tkinter as tk
from tkinter import *
from tkinter.tix import Tk, Control, ComboBox  #升级的组合控件包
from tkinter.messagebox import showinfo, showwarning, showerror #各种类型的提示框
from tkinter import ttk
from tkinter import font
import tkinter.font as tkFont

from web3.auto import w3
from eth_account.messages import encode_defunct

import web3, json, requests
from web3 import Web3, HTTPProvider

from addrETH import *



class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()
        self.keys = {}


    def create_widgets(self):
        is_Num = self.register(self.isNum)

        ## 创建第一个容器
        fm1 = tk.Frame(padx='10')   
        fm1.pack(side='top', fill='both', expand='YES')
        tk.Label(fm1, width='16', text='from : ').pack(side='left', expand='NO')
        self.from0 = tk.StringVar()
        self.com1 = ttk.Combobox(fm1, textvariable=self.from0, state="readonly")
        self.com1.pack(side='right', fill='x' ,expand='YES')

        self.to = tk.StringVar()
        self.to.set("0x2e8709DD4528d460a1e7fb07dbc901741942a911") ## WA2301 Binance account!!!
        fm2 = tk.Frame(padx='10')   
        fm2.pack(side='top', fill='both', expand='YES')
        tk.Label(fm2,width='16', text='to : ').pack(side='left', expand='NO')
        self.e2 = tk.Entry(fm2,textvariable=self.to)
        self.e2.pack(side='right', fill='x' ,expand='YES')
        
        self.value = tk.StringVar()
        self.value.set("1000000000")
        fm3 = tk.Frame(padx='10')   
        fm3.pack(side='top', fill='both', expand='YES')
        tk.Label(fm3, width='16',text='value(Gwei) : ').pack(side='left', expand='NO')
        self.e3 = tk.Entry(fm3,textvariable=self.value, validate='key',validatecommand=(is_Num, '%P'))
        self.e3.pack(side='right', fill='x' ,expand='YES')


        self.gasPrice = tk.StringVar()
        self.gasPrice.set("12")
        fm4 = tk.Frame(padx='10')   
        fm4.pack(side='top', fill='both', expand='YES')
        tk.Label(fm4, width='16',text='gasPrice(Gwei) : ').pack(side='left', expand='NO')
        self.e4 = tk.Entry(fm4,textvariable=self.gasPrice, validate='key',validatecommand=(is_Num, '%P'))
        self.e4.pack(side='right', fill='x' ,expand='YES')


        self.gasLimit = tk.StringVar()
        self.gasLimit.set("21000")
        fm5 = tk.Frame(padx='10')   
        fm5.pack(side='top', fill='both', expand='YES')
        tk.Label(fm5, width='16',text='gasLimit : ').pack(side='left', expand='NO')
        self.e5 = tk.Entry(fm5,textvariable=self.gasLimit, validate='key',validatecommand=(is_Num, '%P'))
        self.e5.pack(side='right', fill='x' ,expand='YES')


        self.nonce = tk.StringVar()
        self.nonce.set("")
        fm6 = tk.Frame(padx='10')   
        fm6.pack(side='top', fill='both', expand='YES')
        tk.Label(fm6, width='16',text='nonce : ').pack(side='left', expand='NO')
        self.e6 = tk.Entry(fm6,textvariable=self.nonce, validate='key',validatecommand=(is_Num, '%P'))
        self.e6.pack(side='right', fill='x' ,expand='YES')


        self.chainId = tk.StringVar()
        self.chainId.set("1")
        fm7 = tk.Frame(padx='10')   
        fm7.pack(side='top', fill='both', expand='YES')
        tk.Label(fm7, width='16',text='chainId : ').pack(side='left', expand='NO')
        self.e7 = tk.Entry(fm7,state = 'disable',textvariable=self.chainId, validate='key',validatecommand=(is_Num, '%P'))
        self.e7.pack(side='right', fill='x' ,expand='YES')



        fm9 = tk.Frame(padx='10')   
        fm9.pack(side='top', fill='both', expand='YES')
        tk.Button(fm9, text='Sign Transaction',command=self.sign_transaction).pack(side='bottom', expand='YES')




    def sign_transaction(self):
        if self.to.get() == "" or self.value.get() == "" or self.gasPrice.get()== "" or self.gasLimit.get() == "" or self.nonce.get() == "" or self.chainId.get()=="":
            tk.messagebox.showerror(title="Error" ,message="Please complete transaction !")
            return  

        transaction = {}
        transaction["from"] = self.from0.get()
        transaction["to"] = self.to.get()
        transaction["value"] = 1000000000*int(self.value.get())
        transaction["gasPrice"] = 1000000000*int(self.gasPrice.get())
        transaction["gas"] = int(self.gasLimit.get())
        transaction["nonce"] = int(self.nonce.get())
        transaction["chainId"] = int(self.chainId.get())

        if not web3.eth.is_checksum_address(transaction["to"]) :
            tk.messagebox.showerror(title="Error" ,message="Receive account is invalid !")
            return

        prikey = self.keys.get(transaction["from"])
        signed = w3.eth.account.sign_transaction(transaction, prikey)

        # data = signed.rawTransaction.hex()

        jsonData = {}
        jsonData["jsonrpc"] = "2.0"
        jsonData["method"] = "eth_sendRawTransaction"
        jsonData["params"] = [signed.rawTransaction.hex()]
        jsonData["id"] = 5


        text = json.dumps(jsonData)

        # print(text)
        pyqrcode.create(text.encode("utf-8")).show()
        

        


    def isNum(self,content):
        # 如果不加上==""的话，就会发现删不完。总会剩下一个数字
        if len(content) > 14:
            return False 
        if content.isdigit() or content == "":
            return True
        else:
            return False








def main():
    wif = "c768acec72b8605462d0160e9635c9d1df4863b224404c11a75544425b252648"


    window = tk.Tk()
    window.title("ETH Cold Wallet")
    window.geometry("520x320+600+100") 
    window.resizable(0,0) # 禁止拉伸窗口
    window.attributes("-type", 0) # 去掉窗口最大化最小化按钮，只保留关闭

    app = Application(master=window)

    obj = addrETH("")
    pubkey = obj.getPubkey(wif)
    addr = obj.getAddr(pubkey)
    app.keys[addr] = wif
    app.com1["value"] = list(app.keys.keys())
    app.com1.current(0)
    app.mainloop()

 

if __name__ == '__main__':
    main()